import os
import shutil
import json
from pathlib import Path
import argparse
from m12_query_fileinzip import query_db_for_file
from m11_fileinzip_detail import query_zip_file
from m01_file_detail import query_hash_size

def is_photo_file(filename):
    """判断给定的文件是否为视频文件"""
    image_extensions = {'.jpg', '.jpeg', '.png','.aae','.heic','.thm', '.gif', '.bmp', '.tiff', '.webp'}
    return Path(filename).suffix.lower() in image_extensions


def main(db_dir, scan_dir, del_dir):
    for root, _, files in os.walk(scan_dir):
        for file_name in files:
            file_path = os.path.join(root, file_name)
            # Get file details
            file_details = query_hash_size(file_path)
            # print(f"file_details:{file_details};")
            if "error" in file_details:
                continue
            json_file_details = json.loads(file_details)
            hash_value = json_file_details["hash"]
            size = json_file_details["size"]
            # print(f"hash_value:{hash_value}; size:{size}")

            if not hash_value or not size:
                print(f"Failed to retrieve hash or size for file {file_path}")
                continue

            # Query database
            db_result = query_db_for_file(db_dir, 'file_hashes.db', 'photo_hash', hash_value)
            # print(f"db_result:{db_result};")
            if "error" in db_result:
                continue
            
            # Get file details
            json_db_result = json.loads(db_result)
            zip_path = json_db_result["zip_path"]
            zip_name = json_db_result["zip_name"]
            photo_path = json_db_result["file_path"]
            photo_name = json_db_result["file_name"]
            # print(f"photo_path:{photo_path}; photo_name:{photo_name}")
            if not is_photo_file(photo_name) :
                continue
            # 根据photo_path是否为"."来决定如何构建文件路径
            if photo_path == ".":
                final_photo_path = photo_name
            else:
                final_photo_path = os.path.join(photo_path, photo_name)

            fileinzip_details = query_zip_file(os.path.join(db_dir, zip_path, zip_name), final_photo_path)
            # print(f"fileinzip_details:{fileinzip_details};")
            if "error" in fileinzip_details:
                continue
            
            json_fileinzip_details = json.loads(fileinzip_details)
            photo_size = json_fileinzip_details["size"]
            photo_hash = json_fileinzip_details["hash"]
            
            if  photo_size== size and photo_hash == hash_value:
                # Compute the relative path of the file with respect to scan_dir
                rel_path = os.path.relpath(root, scan_dir)
                dest_dir = os.path.join(del_dir, rel_path)
                
                # Create the destination directory if it doesn't exist
                os.makedirs(dest_dir, exist_ok=True)
                
                # Move the file to the corresponding directory structure in del_dir
                dest_path = os.path.join(dest_dir, file_name)
                shutil.move(file_path, dest_path)
                print(f"File {file_path} successfully moved to {dest_path}")
            else:
                print(f"Check failed - file {file_path}/{file_name} , File Size: {size}, Hash Value: {hash_value}")
                print(f"Database filename: {photo_path}/{photo_name} in {zip_path}/{zip_name}, File Size: {photo_size}, Hash Value: {photo_hash}")
            

if __name__ == '__main__':
    parser = argparse.ArgumentParser(description='Photo file removal tool')
    parser.add_argument('--db', type=str, default='D:\\photo\\base', help='SQLite database and base folder directory A')
    parser.add_argument('--scan-dir', type=str, default='D:\\photo\\temp', help='Directory B to scan for files')
    parser.add_argument('--del-dir', type=str, default='D:\\photo\\del', help='Directory C where files will be moved for deletion')

    args = parser.parse_args()
    
    main(args.db, args.scan_dir, args.del_dir)

#e.g. python .\photo_remove.py --db D:\temp\base --scan-dir D:\temp\photo_tmp --del-dir D:\temp\photo_del